package org

import (
	"errors"
	"strings"
	"time"
	"dhfshop/models"
	"dhfshop/models/consts"
	"github.com/astaxie/beego/orm"
)

//门店
type Store struct {
	StoreId      int64   `orm:"column(store_id);pk;auto" json:"store_id" form:"store_id"` 
	PartnerId    int64   `orm:"column(partner_id);index" json:"partner_id" form:"partner_id"`       //
	Name         string  `orm:"column(name)" json:"name" form:"name"`       // 
	Address      string  `orm:"column(address);type(text)" json:"address" form:"address"`       // 
	IndustryCode int     `orm:"column(industry_code);default(1)" json:"industry_code" form:"industry_code"` //行业类别1电商类(默认);2餐饮类;3美容美发类;4便利店类
	Phone        string  `orm:"column(phone)" json:"phone" form:"phone"`          //电话
	Mobile       string  `orm:"column(mobile)" json:"mobile" form:"mobile"`       //手机 
	ZipCode      string  `orm:"column(zip_code)" json:"zip_code" form:"zip_code"` //邮编 
	LogoImg      string  `orm:"column(logo_img);null" json:"logo_img" form:"logo_img"`   // 
	OrderIndex   int     `orm:"column(order_index)" json:"order_index" form:"order_index"`       //
    State        int     `orm:"column(state)" json:"state" form:"state"`     // 
	Longitude    float64 `orm:"column(longitude)" json:"longitude" form:"longitude"`     // 经度,范围为-180~180,负数表示西经
	Latitude     float64 `orm:"column(latitude)" json:"latitude" form:"latitude"`     // 维度,范围为-90~90,负数表示南纬
	LocationSwitch int   `orm:"column(location_switch);default(1)" json:"location_switch" form:"location_switch"`  //参加地理位置切换，1=不参加，2=参加
	DeliverRadius  int   `orm:"column(deliver_radius)" json:"deliver_radius" form:"deliver_radius"`                //配送最大半径(公里)
	CreatedAt    time.Time `orm:"auto_now_add;column(created_at);type(datetime)" json:"-" form:"-"`   /* 创建时间 */
	CreatedAtStr   string    `orm:"-" json:"created_at"`
	IsMain       int     `orm:"column(is_main);default(2)" json:"is_main" form:"is_main"` //1主门店,大于等于2代表是子门店,一个partner只能有1个门店是1的情况
	Config      string  `orm:"column(config);type(text)" json:"config" form:"config"` //存储一些门店相关的配置参数 
}


func init() {
    orm.RegisterModel(new(Store))   
}

func AddStore(m *Store) (id int64, err error) {
	o := models.GetDefaultDB()
	id, err = o.Insert(m)
	return
}

func AddMultiStores(list []*Store) (err error) {
    o := models.GetDefaultDB()
    size := len(list)
	if size > 1 {
	    _, err = o.InsertMulti(size, list) 
	}else{
	   _, err = o.Insert(list[0])
	}
	return
}

func GetStoreById(id int64) (v *Store, err error) {
	o := models.GetDefaultDB()
	v = &Store{StoreId: id}
	if err = o.Read(v); err == nil {
		v.CreatedAtStr = v.CreatedAt.Format(consts.DATETIME_FORMAT)
		return v, nil
	}
	return nil, err
}

func GetStoreByPartnerId(id int64) (v *Store, err error) {
	o := models.GetDefaultDB()
	v = &Store{PartnerId: id}
	if err = o.Read(v, "PartnerId"); err == nil {
		v.CreatedAtStr = v.CreatedAt.Format(consts.DATETIME_FORMAT)
		return v, nil
	}
	return nil, err
}

func GetAllStores(storeIds []int64,query map[string]string, fields []string, order_by map[string]string, 
    offset int, limit int) ([]*Store, int64,error) {
	o := models.GetDefaultDB()
	qs := o.QueryTable(new(Store))
	for k, v := range query {
		k = strings.Replace(k, ".", "__", -1)
		qs = qs.Filter(k, v)
	}
	if len(storeIds) > 0 {
        qs = qs.Filter("store_id__in", storeIds)
    }
	cnt, err := qs.Count()
	// order by:
	var sortFields []string
	for k, v := range order_by {
		orderby := ""
		if v == "desc" {
			orderby = "-" + k
		} else if v == "asc" {
			orderby = k
		} else {
			return nil, 0, errors.New("Error: Invalid order. Must be either [asc|desc]")
		}
		sortFields = append(sortFields, orderby)
	}
	qs = qs.OrderBy(sortFields...)
	var lists []*Store
	if _, err := qs.Limit(limit, offset).All(&lists, fields...); err == nil {
		for _, store := range lists {
			store.CreatedAtStr = store.CreatedAt.Format(consts.DATETIME_FORMAT)
	    }
		return lists, cnt, nil
	}
	return nil, 0, err
}

func UpdateStoreById(m *Store, k ...string) (err error) {
	o := models.GetDefaultDB()
	v := Store{StoreId: m.StoreId}
	if err = o.Read(&v); err != nil {
		return err
	}else{
	    if _, err = o.Update(m, k...); err != nil {
		   return err
		}
	}
	return nil
}

func DeleteStore(id int64) (err error) {
	o := models.GetDefaultDB()
	v := Store{StoreId: id}
	if err = o.Read(&v); err == nil {
		if _, err = o.Delete(&v); err == nil {
			return nil
		}
	}
	return
}

func CheckMainStoreExist(partnerId int64) bool {
	o := models.GetDefaultDB()
	exist := o.QueryTable(new(Store)).Filter("partner_id",partnerId).Filter("is_main",1).Exist()
	return exist
}
